﻿using UnityEngine;
using System.Collections;

public class LoadingScreenController
{
    private LoadingScreenView view = null;
    private IData persionData = new PersonData();
    

    public LoadingScreenController()
    {
        view = GameObject.Find("LoadingScreen").GetComponent<LoadingScreenView>();       
        listener();  
    }

    public void setResolution(Vector2 value)
    {
        view.GetComponent<RectTransform>().sizeDelta = new Vector2(value.x, value.y);
    }

    private void listener()
    {
        GameStatusModel.GetInstance().OnStatusChangeEvent += OnScreenChange;
    }

    private void OnScreenChange(string value)
    {
        if (value == GameStatusModel.SCREEN_LOADING)
        {
            view.GetComponent<RectTransform>().SetAsLastSibling();
            UpdateFromServer();
        }
    }

    private void UpdateFromServer()
    {
        WWWForm wf = new WWWForm();
        wf.AddField(InitConfig.GetInstance().USER_ID, InitConfig.GetInstance().USER_KEY);
        Loader.GetInstance().SendMessage_POST(InitConfig.GetInstance().SERVER_GET_DATA, wf, getServerData);
    }

    //获取服务器数据
    private void getServerData(WWW www)
    {
        if (www.error == null)
        {
            Debug.LogWarning(www.text);
            //给加载进度添加侦听方法
            persionData.AddPrecentEvent += OnLoading;
            //传入JSON数据
            persionData.Translate2String(www.text, OnCompleteLoading);
            
        }
        else
        {
            Debug.Log(www.error);
        }
    }

    //下载的进度
    private void OnLoading(object value)
    {
        view.setSliderValue = (float)value;
        if ((float)value >= 1)
        {
            view.setSliderValue = 1;
            persionData.AddPrecentEvent -= OnLoading;
        }
    }

    //加载完成时
    private void OnCompleteLoading()
    {
        LoadingModel.GetInstance().ServerData = persionData.GetData();
        GameStatusModel.GetInstance().ScreenStatus = GameStatusModel.SCREEN_PLAY;
    }
}
